/**
  ******************************************************************************
  * File Name          : I2C.c
  * Description        : This file provides code for the configuration
  *                      of the I2C instances.
  ******************************************************************************
  */

/* Includes ------------------------------------------------------------------*/
#include "i2c.h"
#include "delay.h"


I2C_HandleTypeDef hi2c1;

/* I2C1 init function */
void I2C1_Init(void)
{
    hi2c1.Instance = I2C1;
    hi2c1.Init.ClockSpeed = 100000;
    hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;
    hi2c1.Init.OwnAddress1 = 0xa2;                //注：原来是0
    hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
    hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
    hi2c1.Init.OwnAddress2 = 0;
    hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
    hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
	HAL_I2C_Init(&hi2c1);
//    if (HAL_I2C_Init(&hi2c1) != HAL_OK)
//    {
//        _Error_Handler(__FILE__, __LINE__);
//    }
}

void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle)
{
    GPIO_InitTypeDef GPIO_InitStruct;
    if(i2cHandle->Instance==I2C1)
    {  
		HAL_I2C_MspDeInit(i2cHandle);
        /**I2C1 GPIO Configuration    
        PB6     ------> I2C1_SCL
        PB7     ------> I2C1_SDA 
        */
//        GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9;
//        GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
//        GPIO_InitStruct.Pull = GPIO_PULLUP;
//        GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
        GPIO_InitStruct.Alternate = GPIO_AF4_I2C1;
//        HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
		
			
		
		GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9;     //IIC1
		GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;//GPIO_MODE_AF_OD;  GPIO_MODE_OUTPUT_PP   GPIO_MODE_AF_PP       //先设置为推挽输出（i2c需要这种模式）    
		GPIO_InitStruct.Pull = GPIO_NOPULL;		//自加nsj
		GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;//GPIO_SPEED_FREQ_HIGH;    GPIO_SPEED_HIGH
		HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);  
		
		delay_ms(1);
		I2C1->CR1= I2C_CR1_SWRST;          //复位I2C控制器
		I2C1->CR1= 0;              //解除复位（不会自动清除）
		
		GPIO_InitStruct.Pin = GPIO_PIN_8|GPIO_PIN_9;     //IIC1
		GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;//GPIO_MODE_AF_OD;  GPIO_MODE_OUTPUT_PP   GPIO_MODE_AF_PP       //开漏输出（i2c需要这种模式）    
		HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); 

		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		

        /* I2C1 clock enable */
        __HAL_RCC_I2C1_CLK_ENABLE();
    }
}

void HAL_I2C_MspDeInit(I2C_HandleTypeDef* i2cHandle)
{
    if(i2cHandle->Instance==I2C1)
    {
        /* Peripheral clock disable */
        __HAL_RCC_I2C1_CLK_DISABLE();
  
        /**I2C1 GPIO Configuration    
        PB6     ------> I2C1_SCL
        PB7     ------> I2C1_SDA 
        */
        HAL_GPIO_DeInit(GPIOB, GPIO_PIN_8|GPIO_PIN_9);
  }
}

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
